package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;

import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ly
 * @Date: 2021/07/29/21:01
 * @Description:
 */


/*
*
* 查询今日佳人
*
* */
@Service
public class TodayBestService {


    //用于检验token
    @Autowired
    private UserService userService;

    @Autowired  //查询今日佳人
    private RecommendUserService recommendUserService;

    //用于补全佳人信息
    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;


    public TodayBest queryTodayBest() {
      /*  //校验token是否有效，通过SSO的接口进行校验
        User user = userService.queryUserByToken(token);
        if (user == null) {
            //token 过期或者非法
            return null;
        }*/
        User user = UserThreadLocal.get();


        //查询推荐用户（今日佳人）
        //负责与dubbo交互
       TodayBest todayBest= recommendUserService.queryTodayBest(user.getId());
          if (todayBest==null){

              //如果没查询到推荐用户，那么就会系统给出一个默认的用户
              todayBest = new TodayBest();
              todayBest.setId(defaultUser);
              todayBest.setFateValue(80L); //固定值
          }


          //补全信息（补全查询到的佳人的信息）
       UserInfo userInfo= userInfoService.queryUserInfoByUserId(todayBest.getId());
          if (userInfo==null){
              return null;
          }
      //  todayBest.setId(userInfo.getUserId());
        todayBest.setAvatar(userInfo.getLogo());  //设置头像
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
        todayBest.setGender(userInfo.getSex().getValue()==1? "man" :"woman");
        todayBest.setAge(userInfo.getAge());
        return todayBest;

    }







    /**
     * 查询推荐用户列表
     *
     * @param queryParam
     * @param
     * @return
     */

    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
      /*  //校验token是否有效，通过SSO的接口进行校验
        User user = userService.queryUserByToken(token);
        if (user==null){
            return null; //token已过期，或者token非法
        }*/

        User user = UserThreadLocal.get();

        PageResult pageResult=new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());





        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(),
                                                                  queryParam.getPage(),
                                                                  queryParam.getPagesize());

        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            //没有查询到推荐的用户列表
            return pageResult;
        }

        //填充个人信息
         //收集推荐用户的id

        Set<Long> userIds =new HashSet<>();
        Map<Long,Double> recommendUsers=new HashMap<>();
        for (RecommendUser record : records) {
            userIds.add(record.getToUserId());
            recommendUsers.put(record.getToUserId(),record.getScore());
        }

        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();

        //用户id参数
        queryWrapper.in("user_id",userIds);

        if (StringUtils.isNotEmpty(queryParam.getGender())) {
            //需要性别参数查询
//            queryWrapper.eq("sex", StringUtils.equals(queryParam.getGender(), "man") ? 1 : 2);
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())) {
            //需要城市参数查询
//            queryWrapper.like("city", queryParam.getCity());
        }

        if (queryParam.getAge() != null) {
            //设置年龄参数，条件：小于等于
//            queryWrapper.le("age", queryParam.getAge());
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        if(CollectionUtils.isEmpty(userInfoList)){
            //没有查询到用户的基本信息
            return pageResult;
        }

        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();

            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setAge(userInfo.getAge());

            //缘分值
            /*for (RecommendUser record : records) {
                if(record.getUserId().longValue() == userInfo.getUserId().longValue()){
                    Double score = Math.floor(record.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(score.longValue());
                    break;
                }
            }*/

            Double floor = Math.floor(recommendUsers.get(userInfo.getId()));
            todayBest.setFateValue(floor.longValue());

            todayBests.add(todayBest);
        }

        //按照缘分值进行倒序排序
        Collections.sort(todayBests, (o1, o2) -> (int)(o2.getFateValue() - o1.getFateValue()));

        pageResult.setItems(todayBests);

        return pageResult;
    }

}